package com.juhuixing.file.server.controller;


import com.google.common.collect.Lists;
import com.juhuixing.common.base.BaseController;
import com.juhuixing.common.base.ResponseData;
import com.juhuixing.common.constant.QiNiuConstant;
import com.juhuixing.common.utils.qiniu.QiniuOperateUtil;
import com.juhuixing.file.server.business.service.IFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 * @author 刘猛
 * @since 2019-03-20
 */
@RestController
@Api(tags = "文件上传API")
@RequestMapping("/file")
@Slf4j
public class FileController extends BaseController {

    @Autowired
    private IFileService fileService;

    @ApiOperation(value = "单文件上传接口",notes = "type:上传私有private,公有public")
    @PostMapping("/upload")
    public ResponseData uploadOpen(@RequestParam("file") MultipartFile file,@RequestParam @ApiParam(value = "上传类型") String type) {
        String rs = fileService.upload(file,type);
        if(StringUtils.isBlank(rs)){
            ResponseData.fail("文件上传失败",403);
        }
        return ResponseData.ok(rs);
    }

    @ApiOperation("访问私有云文件(测试)")
    @GetMapping("/get")
    public ResponseData get() {
        String path = QiNiuConstant.QI_NIU_PRIVATE_ADDRESS +"zhengque282721256495636480.mp3";
        return ResponseData.ok(QiniuOperateUtil.getDownloadToken(path));
    }

    @ApiOperation(value = "多文件上传接口",notes = "type:上传私有private,公有public")
    @PostMapping("/uploadBatch")
    public ResponseData uploadOpenBatch(@RequestParam("files") MultipartFile[] files,@RequestParam String type) {
        List<String> urls = Lists.newArrayList();
        if(ArrayUtils.isNotEmpty(files)){
            Arrays.stream(files).forEach(file ->{
                urls.add(fileService.upload(file,type));
            });
        }
        if(CollectionUtils.isEmpty(urls)){
            ResponseData.fail("文件上传失败",403);
        }
        return ResponseData.ok(urls);
    }

    @ApiOperation("七牛云公有上传token")
    @GetMapping("/get/public/token")
    public ResponseData getPublicToken() {
        return ResponseData.ok(QiniuOperateUtil.getUploadToken());
    }

    @ApiOperation("七牛云私有上传token")
    @GetMapping("/get/private/token")
    public ResponseData getPrivateToken() {
        return ResponseData.ok(QiniuOperateUtil.getPrivateUploadToken());
    }



}

